package com.xu.easyexcel.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashSet;
import java.util.Set;

public class NIOServer {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel srvSocketChannel = ServerSocketChannel.open();
        srvSocketChannel.configureBlocking(false);
        ServerSocket socket = srvSocketChannel.socket();
        socket.setReuseAddress(true);
        socket.bind(new InetSocketAddress("localhost",8899));

        Selector selector = Selector.open();
        srvSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        Set<SocketChannel> channelGroup = new HashSet<>();

        while (selector.select() > 0) {
            Set<SelectionKey> keys = selector.selectedKeys();

            for (SelectionKey key : keys) {
                SocketChannel client;
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    client = channel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                    channelGroup.add(client);
                    System.out.println(client.getRemoteAddress());
                } else if (key.isReadable()) {
                    client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    client.read(buffer);
                    buffer.flip();
                    System.out.print("收到客户端："+new String(buffer.array()));
                    channelGroup.forEach(channel -> {
                        buffer.rewind();
                        if (channel != client) {
                            try {
                                int port = client.socket().getPort();
                                byte[] array = buffer.array();
                                String s = "client{" + port + "}:" + new String(array);
                                channel.write(ByteBuffer.wrap(s.getBytes()));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                keys.remove(key);
            }
        }
    }
}
